import Vue from "vue";
import VueRouter from "vue-router";
import routes from "./routes";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import store from "@/store";

Vue.use(VueRouter);

const router = new VueRouter({
  mode: "history",
  routes,
});

const whileList = ["Home", "Login", "Register", "Search", "Detail"];
//进度条的配置
//使用全局前置守卫配置开启进度条
router.beforeEach(async (to, from, next) => {
  NProgress.start();

  const token = store.state.User.token;
  //当token存在
  if (token) {
    if (to.name === "Login") {
      next("/home");
    } else {
      const isUserMessage = !!store.state.User.userMessage.nickName;
      if (isUserMessage) {
        next();
      } else {
        try {
          await store.dispatch("User/get_userMessage");
          next();
        } catch (e) {
          store.commit("User/remove_token");
          next("/login");
        }
      }
    }
  } else {
    //当token不存在，判断去的地址是否需要登录 需要则跳转到登录 不需要就放行
    if (!whileList.includes(to.name)) {
      next("/login");
    }
    next();
  }
});
//使用全局后置钩子配置关闭进度条
router.afterEach(() => {
  NProgress.done();
});
export default router;
